package com.ebeitech.camera;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.doorapp.R;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class HandWrite extends View {

	Paint paint = null;
	private int screenWidth;
	private int screenHeight;
	private Bitmap originalBitmap = null;
	private Bitmap newBitmap = null;
	private float clickX = 0, clickY = 0;
	private float startX = -1, startY = -1;
	private boolean isMove = false;
	private int color = Color.RED;
	private float strokeWidth = 4.0f;
	private String picPath = null;
	private Rect viewRect = null;
	private Rect imageRect = null;
	Paint photoPaint = null;// create paint
	private boolean doModified = false;
	private CommonAlertDialogFragment progressDialog = null;
	private boolean isClear;

	private OnModifyListener mModifyListener;

	public void setOnModifyListener(OnModifyListener l) {
		mModifyListener = l;
	}

	public int getPictureWidth() {
		return originalBitmap.getWidth();
	}

	public int getPictureHeight() {
		return originalBitmap.getHeight();
	}

	public HandWrite(Context context, AttributeSet attrs) {
		super(context, attrs);
		// originalBitmap = BitmapFactory.decodeResource(getResources(),
		// R.drawable.t);
		viewRect = new Rect();
		photoPaint = new Paint();
		photoPaint.setDither(true);
		photoPaint.setFilterBitmap(true);

		screenWidth = ViewUtil.getScreenSize((Activity) context).widthPixels;
		screenHeight = ViewUtil.getScreenSize((Activity) context).heightPixels;
	}

	public void setBitmapPath(String path) {
		this.picPath = path;
		LoadBitmapTask task = new LoadBitmapTask();
		task.execute();
	}

	private class LoadBitmapTask extends AsyncTask<Void, Void, Void> {

		/*
		 * (non-Javadoc)
		 *
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog = ViewUtil.showProgressDialog(getContext(),-1, R.string.ebei_please_wait_for_a_sec);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!StringUtil.isStringNullOrEmpty(picPath)) {
				originalBitmap = BitmapFactory.decodeFile(picPath);
				newBitmap = Bitmap.createBitmap(originalBitmap).copy(
						Bitmap.Config.ARGB_8888, true);

			}
			return null;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			ViewUtil.dismissDialog(progressDialog);
			if (newBitmap != null) {
				int imageWidth = newBitmap.getWidth();
				int imageHeight = newBitmap.getHeight();
				imageRect = new Rect(0, 0, imageWidth, imageHeight);
			} else {
				Log.i("tiger log", picPath + "");
				Context c = getContext();
				Activity activity = (Activity) c;
				Toast.makeText(c, R.string.ebei_camera_error_happen, Toast.LENGTH_LONG)
						.show();
				;
				activity.finish();
			}

			int imageWidth = originalBitmap.getWidth();
			int imageHeight = originalBitmap.getHeight();
			RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
			if(screenWidth * imageHeight > screenHeight * imageWidth) {
				lp.width = imageWidth * screenHeight / imageHeight;
				lp.height = screenHeight;
			} else {
				lp.width = screenWidth;
				lp.height = imageHeight * screenWidth / imageWidth;
			}
			viewRect.left = 0;
			viewRect.top = 0;
			viewRect.right = lp.width;
			viewRect.bottom = lp.height;
			setLayoutParams(lp);

			invalidate();
		}
	}

	public void clear() {
		isClear = true;
		if (doModified) {
			newBitmap = Bitmap.createBitmap(originalBitmap).copy(
					Bitmap.Config.ARGB_8888, true);
			int imageWidth = newBitmap.getWidth();
			int imageHeight = newBitmap.getHeight();

			imageRect = new Rect(0, 0, imageWidth, imageHeight);
			invalidate();
			doModified = false;
		}
	}

	public void setstyle(float strokeWidth) {
		this.strokeWidth = strokeWidth;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (imageRect == null) {
			return;
		}
		HandWriting();

		if (originalBitmap == null) {
			return;
		}

		int viewWidth = viewRect.width();
		int viewHeight = viewRect.height();
		int imageWidth = originalBitmap.getWidth();
		int imageHeight = originalBitmap.getHeight();

		if (newBitmap == null
				|| (viewRect.height() != imageRect.height() || viewRect.width() != viewRect
				.width())) {
			newBitmap = Bitmap.createBitmap(viewWidth, viewHeight,
					Bitmap.Config.ARGB_8888)
					.copy(Bitmap.Config.ARGB_8888, true); // create an empty new
			// bitmap
			Canvas c = new Canvas(newBitmap);// create a canvas

			Rect src = new Rect(0, 0, imageWidth, imageHeight);
			Rect dst = new Rect(0, 0, viewWidth, viewHeight);
			c.drawBitmap(originalBitmap, src, dst, photoPaint);
			imageRect.top = 0;
			imageRect.bottom = imageRect.top + newBitmap.getHeight();
			imageRect.left = 0;
			imageRect.right = imageRect.left + newBitmap.getWidth();
		}
		canvas.drawBitmap(newBitmap, imageRect, viewRect, null);
		// canvas.drawBitmap(newBitmap, 0, 0, null);

		if (isClear && mModifyListener != null) {
			mModifyListener.onClear();
			isClear = false;
		}
	}

	public void HandWriting() {
		if (newBitmap == null) {
			return;
		}

		Canvas canvas = null;

		canvas = new Canvas(newBitmap);

		paint = new Paint();
		paint.setStyle(Style.STROKE);
		paint.setAntiAlias(true);
		paint.setColor(color);
		paint.setStrokeWidth(strokeWidth);
		if (isMove) {
			if (-1 != startX && -1 != startY) {
				canvas.drawLine(startX, startY, clickX, clickY, paint);
				if (!doModified) {
					doModified = true;
				}
				if (doModified && mModifyListener != null) {
					mModifyListener.onModify();
				}
			}
		}

		startX = clickX;
		startY = clickY;

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		clickX = event.getX();
		clickY = event.getY();
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN) {

			startX = clickX;
			startY = clickY;
			isMove = false;
			invalidate();
			return true;
		} else if (action == MotionEvent.ACTION_MOVE) {
			isMove = true;
			invalidate();
			return true;
		} else if (action == MotionEvent.ACTION_DOWN) {
			isMove = false;
			startX = -1;
			startY = -1;
			clickX = -1;
			clickY = -1;
		}

		return super.onTouchEvent(event);
	}

	public String saveBitmap() {
		if (StringUtil.isStringNullOrEmpty(this.picPath)) {
			Toast.makeText(this.getContext(), R.string.ebei_camera_error_happen,
					Toast.LENGTH_LONG).show();
			return null;
		}

		if (newBitmap == null) {
			newBitmap = Bitmap.createBitmap(originalBitmap).copy(
					Bitmap.Config.ARGB_8888, true);
		}
		int width = originalBitmap.getWidth();
		int height = originalBitmap.getHeight();
		Bitmap icon = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888); // create an empty new bitmap
		Canvas canvas = new Canvas(icon);// create a canvas

		// Rect src = new Rect(0, 0, newBitmap.getWidth(),
		// newBitmap.getHeight());
		Rect dst = new Rect(0, 0, width, height);
		canvas.drawBitmap(newBitmap, null, dst, photoPaint);

		/*String dateStr = PublicFunctions.milMillis2String(new Date().getTime(),
				"yyyy-MM-dd HH:mm:ss");

		Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
				| Paint.DEV_KERN_TEXT_FLAG);
		textPaint.setTextSize(30.0f);
		textPaint.setTypeface(Typeface.DEFAULT_BOLD);
		textPaint.setColor(Color.RED);
		float dateWidth = textPaint.measureText(dateStr);
		FontMetrics fm = textPaint.getFontMetrics();
		float textHeight = fm.descent - fm.ascent;
		canvas.drawText(dateStr, width - dateWidth - 50, height -  textHeight/2, textPaint);
		// 左边显示名称
		String userName = QPIApplication.getString(QPIConstants.USER_NAME, "");
		String logo = QPIApplication.getString(QPIConstants.LOGO, "");
		canvas.drawText(userName, 20, height - textHeight/2, textPaint);
		canvas.drawText(logo, 20, height - textHeight*2, textPaint);*/
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();

		if (newBitmap != icon && !newBitmap.isRecycled()) {
			newBitmap.recycle();
			newBitmap = null;
		}

		String tempPath = null;
		if (doModified) {
			tempPath = picPath;
			picPath = PublicUtil.getAppFile(getContext()) + "/" + TimeUtil.getCurrentTime("yyyyMMdd_HHmmss") + ".jpg";
		}
		File f = new File(picPath);
		try {
			if (!f.exists()) {
				f.createNewFile();
			}
			FileOutputStream fOut = new FileOutputStream(f);
			icon.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
			fOut.flush();
			fOut.close();
			if (!StringUtil.isStringNullOrEmpty(tempPath)) {
				f = new File(tempPath);
				if (f.exists()) {
					f.delete();
				}
			}
			if (icon != null && !icon.isRecycled()) {
				icon.recycle();
				icon = null;
			}

			if (originalBitmap != null && !originalBitmap.isRecycled()) {
				originalBitmap.recycle();
				originalBitmap = null;
			}
			return picPath;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 	return current bitmap for save as picture
	 * @return Bitmap
	 */
	public Bitmap getCurrentBitmap(){
		if (StringUtil.isStringNullOrEmpty(this.picPath)) {
			Toast.makeText(this.getContext(), R.string.ebei_camera_error_happen,
					Toast.LENGTH_LONG).show();
			return null;
		}

		if (newBitmap == null) {
			newBitmap = Bitmap.createBitmap(originalBitmap).copy(
					Bitmap.Config.ARGB_8888, true);
		}
		int width = originalBitmap.getWidth();
		int height = originalBitmap.getHeight();
		Bitmap icon = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888); // create an empty new bitmap
		Canvas canvas = new Canvas(icon);// create a canvas

		// Rect src = new Rect(0, 0, newBitmap.getWidth(),
		// newBitmap.getHeight());
		Rect dst = new Rect(0, 0, width, height);
		canvas.drawBitmap(newBitmap, null, dst, photoPaint);
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();

		return icon;
	}
	/**
	 * @return the color
	 */
	public int getColor() {
		return color;
	}

	/**
	 * @param color
	 *            the color to set
	 */
	public void setColor(int color) {
		this.color = color;
	}

	/**
	 * @return the strokeWidth
	 */
	public float getStrokeWidth() {
		return strokeWidth;
	}

	/**
	 * @param strokeWidth
	 *            the strokeWidth to set
	 */
	public void setStrokeWidth(float strokeWidth) {
		this.strokeWidth = strokeWidth;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.view.View#onLayout(boolean, int, int, int, int)
	 */
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
							int bottom) {
		// TODO Auto-generated method stub
		super.onLayout(changed, left, top, right, bottom);

		if (changed) {
			viewRect.left = 0;
			viewRect.top = 0;
			viewRect.right = right;
			viewRect.bottom = bottom;
			invalidate();
		}
	}

	public interface OnModifyListener {
		void onModify();
		void onClear();
	}

}
